package com.cx.auth.config.custom.sms;

import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * @author: zhangcx
 * @Description: 短信自定义redis token key的生成规则
 * @date: 2024/1/4 13:51
 * @email: zhangcx@bluemoon.com.cn
 */


public class SmsAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {
    private static final String CLIENT_ID = "client_id";
    private static final String SCOPE = "scope";
    private static final String USERNAME = "username";

    private static final String SMS_GRANT_TYPE = "sms_code";

    private static final String SMS_PHONE= "phone";

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<>(authorizationRequest.getScope())));
        }
        values.put(SMS_GRANT_TYPE, authentication.getOAuth2Request().getRequestParameters().get("code"));
        values.put(SMS_PHONE, authentication.getOAuth2Request().getRequestParameters().get(SMS_PHONE));
        return generateKey(values);
    }
}
